import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';

import 'default_error.dart';
import 'form_modal.dart';
import 'package:test_app/core/design_system/extensions/extensions.dart';

/// 文本输入组件（使用原生 TextFormField 实现）
Widget buildInputFieldWidget({
  required FormModal item,
  required GlobalKey<FormBuilderFieldState> fieldKey,
  Widget Function(Widget label, Widget field)? containerBuilder,
}) {
  // 默认必填校验
  final defaultValidator = FormBuilderValidators.compose([
    FormBuilderValidators.required(errorText: '${item.label}不能为空'),
  ]);

  // 将 dynamic 初始值转成 String，避免类型不匹配
  final initialValue = _toStringValue(item.defaultValue);

  return FormBuilderField<String>(
    name: item.field,
    key: fieldKey,
    initialValue: initialValue,
    validator:
        item.validator ?? ((item.require ?? false) ? defaultValidator : null),
    builder: (fieldState) {
      final errorText = fieldState.errorText ?? '';

      final input = TextFormField(
        initialValue: fieldState.value,
        onChanged: fieldState.didChange,
        textAlign: TextAlign.right,
        decoration: InputDecoration(
          hintMaxLines: 1,
          focusedErrorBorder: InputBorder.none,
          hintText: item.placeholder ?? '请输入${item.label}',
          hintStyle: const TextStyle(color: Colors.grey),
          border: InputBorder.none,
          filled: false,
          contentPadding: const EdgeInsets.symmetric(vertical: 0),
          // 关闭内置 errorText，改用统一的 DefaultError 组件
          errorText: null,
        ),
      );

      final labelWidget = Text(item.label).padRight(20);
      final fieldWidget = Expanded(child: input);

      // 如果配置了自定义容器，则优先使用
      final row = item.containerBuilder != null
          ? item.containerBuilder!(labelWidget, fieldWidget)
          : containerBuilder != null
          ? containerBuilder(labelWidget, fieldWidget)
          : [labelWidget, fieldWidget]
                .toRow()
                .padHorizontal(16)
                .height(58)
                .backgroundColor(const Color(0xFFFFFFFF))
                .clipRadius(8);

      return [
        row,
        if (fieldState.hasError) DefaultError(message: errorText),
      ].toColumn();
    },
  );
}

/// 将任意类型的默认值转换为 String
String? _toStringValue(dynamic value) {
  if (value == null) {
    return null;
  }
  if (value is String) {
    return value;
  }
  return value.toString();
}
